package com.beta.service.impl;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.plugins.Page;
import com.beta.dto.admin.OrderDetailDto;
import com.beta.dto.order.*;
import com.beta.entity.Orders;
import com.beta.mapper.OrdersMapper;
import com.beta.service.IOrderItemsService;
import com.beta.service.IOrderStatusService;
import com.beta.service.IOrdersService;
import com.beta.service.ServiceException;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Orders 表数据服务层接口实现类
 */
@Service
public class OrdersService extends SuperServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IOrderItemsService orderItemsService;
    @Autowired
    private IOrderStatusService orderStatusService;

    @Override
    public OrdersDto getOrder(Integer orderId) {
        if(Objects.isNull(orderId)){
            throw new ServiceException("E40001");
        }
        OrdersDto ordersDto = baseMapper.selectOrderById(orderId);
        List<OrderItemDto> ordersItems = orderItemsService.getOrdersItemsByOrderId(orderId);
        if (CollectionUtils.isNotEmpty(ordersItems)) {
            ordersDto.setOrderItems(ordersItems);
        }
        return ordersDto;
    }

    @Override
    public Page<OrdersDto> getUnpaidOrders(Integer userId, Page<OrdersDto> page) {
        if(Objects.isNull(userId)){
            throw new ServiceException("E00113");
        }
        List<OrdersDto> ordersDtos = baseMapper.getUnpaidOrders(page, userId);
        return ordersPage(ordersDtos, page);
    }

    @Override
    public Page<OrdersDto> getOrders(Integer userId, Page<OrdersDto> page) {
        if (Objects.isNull(userId)) {
            throw new ServiceException("E00113");
        }
        List<OrdersDto> ordersDtos = baseMapper.getOrders(page, userId);
        return ordersPage(ordersDtos, page);
    }

    private Page<OrdersDto> ordersPage(List<OrdersDto> ordersDtos, Page<OrdersDto> page) {
        if (CollectionUtils.isEmpty(ordersDtos)) {
            return page;
        }

        fillOrderItems(ordersDtos);
        page.setRecords(ordersDtos);
        return page;
    }

    private void fillOrderItems(List<OrdersDto> ordersDtos) {
        if (CollectionUtils.isEmpty(ordersDtos)) {
            return ;
        }

        List<Integer> orderIds = ordersDtos.stream().map(OrdersDto::getId).collect(Collectors.toList());
        Map<Integer, List<OrderItemDto>> orderItemsMap = orderItemsService.getOrdersItemsBatchByOrderIds(orderIds);
        ordersDtos.forEach(ordersDto -> {
            ordersDto.setOrderItems(orderItemsMap.get(ordersDto.getId()));
        });
    }

    @Override
    public Orders validateOrder(Integer orderId) {
        if (Objects.isNull(orderId)) {
            throw new ServiceException("E40001");
        }
        Orders orders = selectById(orderId);
        if (Objects.isNull(orders)) {
            throw new ServiceException("E40001", orderId);
        }
        return orders;
    }

    @Override
    public Page<OrdersDto> getDeliveringOrders(Integer userId, Page<OrdersDto> page) {
        if(Objects.isNull(userId)){
            throw new ServiceException("E00113");
        }
        List<OrdersDto> ordersDtos = baseMapper.getDeliveringOrders(page, userId);
        return ordersPage(ordersDtos, page);
    }

    @Override
    public Page<OrdersDto> getCompleteOrders(Integer userId, Page<OrdersDto> page) {
        if (Objects.isNull(userId)) {
            throw new ServiceException("E00113");
        }
        List<OrdersDto> ordersDtos = baseMapper.getCompleteOrders(page, userId);
        return ordersPage(ordersDtos, page);
    }

    @Override
    public OrderStatusCountDto getOrdersStatusCount(Integer userId) {
        if(Objects.isNull(userId)){
            throw new ServiceException("E00113");
        }
        return (baseMapper.getOrderStatusCount(userId));
    }

    @Override
    public Boolean canPay(Integer orderId) {
        Orders order = ordersService.selectById(orderId);
        if (orderStatusService.isPaid(order)) {
            throw new ServiceException("E40013");
        }
        if (orderStatusService.isExpired(order)) {
            throw new ServiceException("E40014");
        }
        if (orderStatusService.isCanceled(order)) {
            throw new ServiceException("E40015");
        }
        return true;
    }

    @Override
    public List<Orders> getPickedButNotReceiptOrders(Date beforePickedDate) {
        if (Objects.isNull(beforePickedDate)) {
            return Collections.emptyList();
        }

        return baseMapper.selectPickedButNotReceiptOrders(beforePickedDate);
    }

    @Override
    public Page<BackendOrderDto> getBackendOrders(Page<BackendOrderDto> page, OrderSearchDto orderSearchDto) {
        String code = orderSearchDto.getCode();
        String name = orderSearchDto.getName();
        String status = orderSearchDto.getStatus();
        String cityCode = orderSearchDto.getCityCode();
        String orderTime1 = orderSearchDto.getOrderTime1();
        String orderTime2 = orderSearchDto.getOrderTime2();
        String payStatus = orderSearchDto.getPayStatus();
        List<BackendOrderDto> backendOrders = baseMapper.getBackendOrders(page,code,name,status,cityCode,payStatus);
        page.setRecords(backendOrders);
        return page;
    }

    @Override
    public OrderDetailDto getOrderDetail(Integer orderId) {
        return baseMapper.getOrderDetail(orderId);
    }

}